package cn.car.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
 * 防止跨站攻击过滤器
 * @author hanzhg 2011-10-10 下午11:49:34
 *
 */
public class XssInj implements Filter {
    private static final Log log = LogFactory.getLog(XssInj.class);
	static String failUrl = null;// 失败后的URL指向
	static String filterFlag = null;// 是否进行过滤
	static String notfilter = null;// 是否进行过滤
	static String[] notfilters=null;
	public void destroy() {
		failUrl = null;
		filterFlag = null;
		notfilter=null;
		log.info("XssInj destroy is ok");
	}
	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String url = request.getRequestURI(); // 取得查询
		//log.debug("XssInj request.getRequestURI()="+url);
		for(int i=0;i<notfilters.length;i++){
			String t = request.getContextPath()+notfilters[i];
			if(url.startsWith(t)){
				filterChain.doFilter(request, response);
				return;
			}
		}
		if(filterFlag.equals("true")){
			Enumeration enumParam = request.getParameterNames();
			boolean retError = false;
			while(enumParam.hasMoreElements()){
				String param=(String)enumParam.nextElement();
				String paramValue = request.getParameter(param);
				if(is_inj(paramValue)){
					retError = true;
					log.debug("param="+param+" ;paramValue="+paramValue);
					break;
				}
			}
			if(retError){
				response.sendRedirect(failUrl);
				return;
			}
		}
		filterChain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		failUrl = filterConfig.getInitParameter("failUrl");
		filterFlag =filterConfig.getInitParameter("filterFlag");
		notfilter=filterConfig.getInitParameter("notfilter");
		if(notfilter!=null){
			notfilters=notfilter.split(",");
		}
		log.info("XssInj init is ok config is failUrl="+failUrl+" , filterFlag="+filterFlag);
	}
	/**
	 * 检测是否含有跨站注入漏洞脚本
	 */
	public static boolean is_inj(String str){
		boolean flg = false;
		String[] checkArr = {"<", ">","javascript", "script","eval","document","iframe","jscript","vbscript","/\\*\\*/", "+", "%","&"};
		if (str == null) {
			return false;
		}
		for (int i = 0; i < checkArr.length; i++) {
			String s = checkArr[i];
			if (str.indexOf(s) != -1) {
				log.error("is_inj valid:"+str);
				flg = true;
			}
		}
		return flg;
	}
}
